<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/5/3
 * Time: 14:06
 */
namespace app\first\model;

use app\admin\model\Pic;
use think\Db;
use think\db\Where;
use think\Model;

class ShopTransfers extends Model {
    protected $autoWriteTimestamp = false;
    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $filed
     * @param bool $out
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where=[],$order='create_time desc',$limit=10,$filed='*',$out=false){
        $list = $this
            ->field($filed,$out)
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where($where)
            ->order($order)
            ->paginate($limit);
//        foreach ($list as $k => &$v){
//            $v['message'] = $message->where('aid','eq',$v['id'])->count();
//            $v['collection'] = $collection->where('aid','eq',$v['id'])->count();
//        }
        return $list;
    }

    /**
     * @param int $uid
     * @param string $title
     * @param int $shop_id
     * @param int $type
     * @param int $amount
     * @param string $out
     * @return bool
     */
    public function addNew($uid=0,$title='',$shop_id=1,$type=1,$amount=0,&$out=''){
        $info = (new Shop())->find($shop_id);
        if(!$info){
            $out = '没有开通商铺';
            return false;
        }
        if(!$info['money']){
            $out = '商铺余额不足';
            return false;
        }
        if($amount){
            if($info['money'] - $amount < 0){
                $out = '提现金额超过商铺余额';
                return false;
            }
        }else{
            $amount = $info['money'];
        }
        $data = [
            'order_id'=>build_order_no1('tran_'),
            'type'=>$type,
            'uid'=>$uid,
            'shop_id'=>$shop_id,
            'title'=>$title,
            'amount'=>$amount,
            'status'=>1,
            'create_time'=>time(),
        ];
        $valid = new \app\first\validate\ShopTransfers();
        if(!$valid->check($data)){
            $out = $valid->getError();
            return false;
        }
        if(!$this->save($data)){
            $out = '申请失败';
            return false;
        }
        return true;
    }

    /**
     * @param $id
     * @param string $out
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function active($id,&$out=''){
        $info = $this->find($id);
        if(!$info){
            $out = '店铺不存在';
            return false;
        }
        if($info['status']!=3){
            $out = '店铺未通过审核，请先通审核在激活';
            return false;
        }
        $user = new Member();
        $_user = $user->field('create_time',true)->find($info['uid']);
        $info->status = 4;
        $_user->is_shop = 1;
        Db::startTrans();
        $result = $info->save();
        $result1 = $_user->save();
        if($result && $result1){
            Db::commit();
            return true;
        }else{
            $out = '店铺激活失败';
            Db::rollback();
            return false;
        }
    }

    /**
     * @param $q
     * @param $where
     * @param $limit
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function search($q,$where,$limit){
//        $list = $this
//            ->field('id,content,create_time')
//            ->where($where)
//            ->whereRaw("match(content) against('+{$q}' in boolean mode)")
//            ->paginate($limit);
        $list = $this
            ->field('id,title,create_time')
            ->where($where)
            ->whereLike('content',"%$q%")
            ->paginate($limit);
//        foreach ($list as &$v){
//            if($v['cid_type']==3){
//                $v['content'] = $this->getFieldById($v['id'],'content');
//            }else{
//                $v['content'] = '';
//            }
//        }
        return $list;
    }


    /**t
     * @param int $city_id
     * @param string $order
     * @param int $limit
     * @param string $filed
     * @param bool $out
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lastList($city_id=0,$order='create_time desc',$limit=10,$filed='*',$out=false){
        $where = new Where;
        $where['status'] = 4;
        if($city_id){
            $where['city_id']=$city_id;
        }
        $list = $this
            ->field($filed,$out)
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where($where)
            ->order($order)
            ->limit($limit)
            ->select();
        return $list;
    }

    /**
     * @param int $id
     * @param string $filed
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneById($id=0,$filed=''){
        $filed = $filed?$filed:'update_time';
        $info = $this->field($filed,true)->find($id);
        $info->hits = $info['hits'] + 1;
        $info->save();
        $res = $this
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where('id','eq',$id)
            ->find();
        return $res;
    }

    /**
     * @param int $uid
     * @param string $filed
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneByUid($uid=0,$filed=''){
        $filed = $filed?$filed:'update_time';
        $info = $this->field($filed,true)
                ->where('uid', 'eq', $uid)
                ->find();
        if(!$info){
            return [];
        }
        $info->hits = $info['hits'] + 1;
        $info->save();
        $res = $this
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where('uid','eq',$uid)
            ->find();
        return $res;
    }


    /**
     * @param $cid
     * @param int $limit
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function likes($cid,$limit=4){
        $_limit = $limit * 5;
        $sql = "SELECT t1.id,t1.title,t1.image,t1.create_time FROM `{$this->getTable()}` AS t1 
          JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `{$this->getTable()}`)-(SELECT MIN(id) 
          FROM `{$this->getTable()}`))+(SELECT MIN(id) FROM `{$this->getTable()}`)) AS id from `{$this->getTable()}` limit {$_limit}) AS 
          t2 on t1.id=t2.id where t1.twice_cate_id = {$cid} and t1.status = 2 ORDER BY t1.id LIMIT {$limit}";
        $list = $this->query($sql);
        return $list;
    }

    public function user(){
        return $this->hasOne('member','id','uid');
    }

    /**
     * @param $value
     * @return array|bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getShopLicenceAttr($value){
        if(empty($value)){
            return '';
        }
        $pic = new Pic();
        return $pic->getUrlsById(explode(',',$value));
    }

    /**
     * @param $value
     * @return bool|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLogoAttr($value){
        if(empty($value)){
            return '';
        }
        $pic = new Pic();
        return $pic->getUrlById($value);
    }
}